import { createSlice, PayloadAction } from '@reduxjs/toolkit'
import { CarItemType } from '../../types'


interface CarType {
	loading: boolean
	carList: CarItemType[]
}

const initialState: CarType = {
	loading: false,
	carList: [],
}

const carSlice = createSlice({
	name: 'carSlice',
	initialState,
	reducers: {
		addCar(state, action: PayloadAction<CarItemType>) {
			// 加入购物车需要验证购物车是否放存在该商品
			// 1. 根据id查询购物车
			const item = state.carList.find(v => v.id === action.payload.id)
			// 2. 存在  合并数量
			if (item) { item.count += action.payload.count }
			// 3. 不存在  添加新数据
			else { state.carList.push(action.payload) }
		},
		switchIsCheck(state, action: PayloadAction<CarItemType>) {
			// 切换状态 
			// 1. 根据id查询购物车
			const item = state.carList.find(v => v.id === action.payload.id)
			// 2. 修改状态
			if (item) item.isChecked = !item.isChecked
		},
		addCarCount(state, action: PayloadAction<CarItemType>) {
			// 数量+
			// 1. 根据id查询购物车
			const item = state.carList.find(v => v.id === action.payload.id)
			// 2. 数量增增
			if (item) item.count++
		},
		subCarCount(state, action: PayloadAction<CarItemType>) {
			// 数量- 
			// 1. 根据id查询购物车
			const item = state.carList.find(v => v.id === action.payload.id)
			// 2. 数量减少
			if (item) item.count--
		},
		deleteCar(state, action: PayloadAction<CarItemType>) {
			// 删除 
			// 1. 根据id删除购物车
			state.carList = state.carList.filter(v => v.id !== action.payload.id)
		}
	}
})

export default carSlice.reducer
export const { addCar, switchIsCheck, addCarCount, subCarCount, deleteCar } = carSlice.actions